﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace ELF.Gateway.Jwt;

public class GatewayJwtService
{
    private readonly IConfiguration _config;
    private readonly SigningCredentials _signingCredentials;

    public GatewayJwtService(IConfiguration config)
    {
        _config = config;
        var key = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(_config["GatewayJwt:SecretKey"]!));
        _signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    }

    public string CreateGatewayToken(ClaimsPrincipal userPrincipal)
    {
        // 从原始JWT中提取关键Claims
        var userId = userPrincipal.FindFirstValue("Id") ??
                    throw new InvalidOperationException("Missing 'sub' claim");
        var userName = userPrincipal.FindFirstValue("Name");
        //var nickname = userPrincipal.FindFirstValue("Name");
        //var roles = userPrincipal.FindAll(ClaimTypes.Role).Select(c => c.Value);

        // 构建网关JWT的Claims
        var claims = new List<Claim>
        {
            new Claim("Id", userId),
            new Claim("Name", userName ?? ""),
        };

        // 添加用户角色（如需）
        //claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

        // 创建令牌
        var token = new JwtSecurityToken(
            issuer: _config["GatewayJwt:Issuer"],
            audience: _config["GatewayJwt:Audience"],
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(5),
            signingCredentials: _signingCredentials
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
